<template>
	<view class="zero-tabs">
		<view class="tabbar" :class="[needSticky ? 'sticky' : '']" :style="{
			background: backgroundColor,
			top: needSticky ? offsetTop + 'rpx' : 0,

			'z-index': zIndex,
		}">
			<scroll-view class="scroll_view tab-bar-scroll-view" :scroll-x="true" :show-scrollbar="false"
				:scroll-left="scrollLeft" :scroll-with-animation="true" @scroll="handleScroll">
				<view class="scroll_view_wrap">
					<template v-if="slider == 'capsule'">
						<view class="slider capsule" :style="[{
			width: sliderWidth + 'px',
			height: capsuleOptions.height ? capsuleOptions.height + 'rpx' : height - 20 + 'rpx',
			background: capsuleOptions.color,
			borderRadius: capsuleOptions.radius ? capsuleOptions.radius + 'rpx' : '50rpx',
			left: sliderLeft + 'px',
		}]"></view>
					</template>
					<view :id="`item${index}`" class="item tab-bar-scroll-view-item"
						:class="{ item_disabled: item.disabled }"
						:style="[{ width: itemWidth ? itemWidth + 'px' : 'auto' }, { padding: padding }, { lineHeight: height + 'rpx' }]"
						v-for="(item, index) in tabs" :key="index" @click.stop="handleClick(index, item)">
						<view class="item_name" :style="[
			{ color: current == index ? selectColor : defaultColor },
			{ fontSize: size + 'rpx' },
			// { fontSize: current == index ? selectSize + 'rpx' : defaultSize + 'rpx' },
		]">
							{{ item.name }}
						</view>
					</view>
					<template v-if="slider == 'line'">
						<view class="slider line" :style="{
			background: selectColor,
			width: customLineWidth ? customLineWidth + 'px' : sliderWidth + 'px',
			left: sliderLeft + 'px',
		}"></view>
					</template>



				</view>
			</scroll-view>
		</view>
		<!-- 占位用，使用fixed时生成一个盒子占位 -->
		<view class="tabbar-holder" v-if="needSticky && fixedHolder" :style="{ height: height + 'rpx' }"></view>
	</view>
</template>
<script>
export default {
	name: 'zero-tabs',
	emits: ['change'],
	props: {
		// 传入数组， 数组元素中必须包含字段，name
		tabs: {
			type: Array,
			default: () => [],
		},
		// 当前选中项
		currentIndex: {
			type: Number,
			default: 0,
		},
		// 背景颜色
		backgroundColor: {
			type: String,
			default: 'transparent',
		},
		// 组件高度,单位默认rpx
		height: {
			type: Number,
			default: 80,
		},
		// paddingTop:padding[0] || 0,paddingRight:padding[1]|| 0,paddingBottom:padding[2] || padding[0] || 0,paddingLeft:padding[3] || padding[1] || 0,
		padding: {
			type: String,
			default: '0 32rpx',
		},
		// 默认字体颜色
		defaultColor: {
			type: String,
			default: '#333333',
		},
		// 选中项颜色
		selectColor: {
			type: String,
			default: '#0396FF',
		},
		// 默认字号,默认rpx
		size: {
			type: Number,
			default: 32,
		},
		// 选中项字号,默认rpx,暂不支持
		// selectSize: {
		// 	type: Number,
		// 	default: 32,
		// },
		// 滑块宽度 默认px
		customLineWidth: {
			type: Number,
			default: 0,
		},
		// 是否启用自动平均分布，当子元素宽度总和小于屏幕宽度时使用
		autoJustify: {
			type: Boolean,
			default: false,
		},
		// 是否启用吸顶
		needSticky: {
			type: Boolean,
			default: false,
		},
		// 吸顶距离
		offsetTop: {
			type: Number,
			default: 0,
		},
		// 吸顶时占位盒子
		fixedHolder: {
			type: Boolean,
			default: true,
		},
		// 启用异步
		async: {
			type: Boolean,
			default: false,
		},
		// 是否显示滑块
		showSlider: {
			type: Boolean,
			default: true,
		},
		// 滑块类型 line || capsule || none
		slider: {
			type: String,
			default: 'line'
		},
		capsuleOptions: {
			type: Object,
			default: () => ({
				// width: 0,
				// height: 0,
				// radius: 0,
				color: '#0396FF',
			}),
		},
		zIndex: {
			type: Number,
			default: 1,
		},
	},
	data() {
		return {
			current: 0,
			desc: true,
			scrollWidth: 0, // 导航区宽度
			scrollLeft: 0, // 横向滚动条位置
			itemWidth: this.width,
			sliderWidth: 0,
			sliderLeft: 0,
		}
	},
	mounted() {
		this.$nextTick(() => {
			this.current = this.currentIndex
			this.getScrollW()
		})
	},
	watch: {
		currentIndex(val) {
			this.current = val
		},
		current(val) {
			this.updateSliderPosition(val)
			// 字体大小的改变会让子元素宽度变化,但重新获取会让scrollLeft不正确
			this.$nextTick(() => {
				// this.getScrollW()
			})
		},
		tabs(val) {
			this.$nextTick(() => {
				this.getScrollW()
			})
		},
	},
	methods: {
		handleScroll(e) {
			console.log('handleScroll', e.detail);
		},
		getScrollW() {
			const query = uni.createSelectorQuery().in(this)
			query
				.select('.tab-bar-scroll-view')
				.boundingClientRect((data) => {
					// 拿到 scroll-view 组件宽度
					this.scrollWidth = data.width
					// this.scrollTop = data.top
				})
				.exec()

			query
				.selectAll('.tab-bar-scroll-view-item')
				.boundingClientRect((data) => {
					// console.log('data', data);
					let dataLen = data.length
					let totalW = 0
					for (let i = 0; i < dataLen; i++) {
						//  scroll-view 子元素组件距离左边栏的距离
						this.tabs[i].left = data[i].left
						//  scroll-view 子元素组件宽度
						this.tabs[i].width = data[i].width
						totalW += this.tabs[i].width
					}
					if (this.autoJustify && totalW < this.scrollWidth) {
						this.itemWidth = this.scrollWidth / this.tabs.length
						this.tabs.forEach((item) => {
							item.width = this.itemWidth
						})
					}
					if (dataLen > 0) {
						this.updateSliderPosition(this.current)
					}

				})
				.exec()
		},
		updateSliderPosition(index) {
			// 获取元素宽度
			this.sliderWidth = this.tabs[index].width;
			// 计算滚动视图的左偏移量，使得滑块能够对齐到选中的标签页上
			this.scrollLeft = this.tabs[index].left - (this.scrollWidth / 2 - this.sliderWidth / 2);
			// 如果自定义滑块宽度
			if (this.customLineWidth) {
				this.sliderLeft = 0;
				for (let i = 0; i < index; i++) {
					this.sliderLeft += this.tabs[i].width
				}
				this.sliderLeft += (this.tabs[index].width - this.customLineWidth) / 2
			} else {
				this.sliderLeft = 0;
				for (let i = 0; i < index; i++) {
					this.sliderLeft += this.tabs[i].width;
				}
			}
		},
		handleClick(index, item) {
			if (item.disabled) return
			if (!this.async) {
				this.current = index
				this.scrollLeft = item.left - (this.scrollWidth / 2 - item.width / 2)
				// this.scrollLeft = item.width
			}
			this.$emit('change', index, item)
		},
	},
}
</script>
<style lang="scss" scoped>
.zero-tabs {
	// padding:10rpx;
	width: 100%;
	max-width: 100vw;
}

.sticky {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 1;
}

.tabbar {
	display: flex;
	flex-flow: row nowrap;
	align-items: center;

	.tab-bar-scroll-view {
		position: relative;
		overflow: hidden;
		white-space: nowrap;

		.scroll_view_wrap {
			display: flex;
			flex-flow: row nowrap;
			align-items: center;
			font-size: 32rpx;
			// line-height: 80rpx;
			z-index: 1;
			position: relative;
		}

		.item {
			box-sizing: border-box;
			display: inline-flex;
			flex-flow: row nowrap;
			align-items: center;
			padding: 0 42rpx;
			justify-content: center;
			white-space: nowrap;
		}

		.item_disabled {
			opacity: 0.5;
		}

		.item_name {}
	}

	.slider {
		position: absolute;
		overflow: hidden;
		transition: left 0.3s, width 0.5s;
		z-index: -1;
	}

	.line {
		bottom: 4rpx;
		height: 4rpx;
		border-radius: 4rpx;
	}

	.capsule {
		top: 50%;
		transform: translateY(-50%);
		overflow: hidden;
		transition: left 0.3s, width 0.5s;
	}
}
</style>